﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXYW.BLL;
using System.Threading;
using WXYW.DAL;
using System.Data;
using System.Configuration;

namespace WXYW.Server
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("服务启动:{0}", DateTime.Now));
            
            while (true)
            {
                try
                {
                    //DataCorrect();
                    if (DateTime.Now.Hour == Convert.ToInt32(ConfigurationManager.AppSettings["ZBTJTime"]))
                    {
                        ZBTJBackgroundService zbtjBService = new ZBTJBackgroundService();
                        Console.WriteLine(string.Format("二次维修统计:{0}", DateTime.Now));
                        zbtjBService.CalculateSecondRepairZB();
                        Console.WriteLine(string.Format("供应商周期统计:{0}", DateTime.Now));
                        zbtjBService.CalculateFactoryZQ();
                        Console.WriteLine(string.Format("备件先行满足率:{0}", DateTime.Now));
                        zbtjBService.CalculateBJXXStatisfyRate();
                        Console.WriteLine(string.Format("备件清理率:{0}", DateTime.Now));
                        zbtjBService.CalculateBJQLRate();
                        Console.WriteLine(string.Format("0ToX指标统计:{0}", DateTime.Now));
                        zbtjBService.Calculate0To5Tat();
                        zbtjBService.Calculate0To3Tat();
                    }

                    if (DateTime.Now.Hour == Convert.ToInt32(ConfigurationManager.AppSettings["WorkTime"]))
                    {
                        SendReminderEmails();
                        SendReminderToEngineer();
                        SendRCReminderToEngineer();
                        GetProductInfo();
                        TransferWXJL();
                        GetCustomerFeedback();
                        CalculateAccessoryUsedTimes();
                        CalculateProductRepairTimes();
                    }
                    Console.WriteLine(string.Format("发送公告通知邮件:{0}", DateTime.Now));
                    SendPostNoticeEmail();
                }
                catch (Exception ex)
                {
                    LogUtility.LogUtilityIntance.LogException(ex, "SendReminderToEngineer");
                    throw ex;
                }                
                Console.WriteLine(string.Format("服务休眠:{0}", DateTime.Now));
                Thread.Sleep((60 - DateTime.Now.Minute) * 60000);                
            }        
        }

        private static void SendReminderToEngineer()
        {
            // 发送维修预警邮件
            Console.WriteLine(string.Format("开始维修预警邮件:{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("开始发送维修预警邮件:{0}", DateTime.Now));
            try
            {
                SendEmailService service = new SendEmailService();
                service.SendEmailForRepairOverdue();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "SendReminderToEngineer");
                throw ex;
            }
        }

        private static void SendRCReminderToEngineer()
        {
            // 发送维修预警邮件
            Console.WriteLine(string.Format("开始返厂维修预警邮件:{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("开始发送返厂维修预警邮件:{0}", DateTime.Now));
            try
            {
                SendEmailService service = new SendEmailService();
                service.SendEmailForFCRepairOverdue();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "SendReminderToEngineer");
                throw ex;
            }
        }

        private static void SendReminderEmails()
        {
            // 发送报价预警邮件
            Console.WriteLine(string.Format("开始发送报价预警邮件:{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("开始发送报价预警邮件:{0}", DateTime.Now));
            try
            {
                SendEmailService service = new SendEmailService();
                service.SendEmailForOverdueQuatationApplication();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "SendReminderEmails");
                throw ex;
            }
        }

        private static void GetProductInfo()
        {
            //更新产品信息
            Console.WriteLine(string.Format("开始更新产品信息::{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("开始更新产品信息::{0}", DateTime.Now));
            SMKFService.WXService webService = new WXYW.Server.SMKFService.WXService();
            webService.Url = ConfigurationManager.AppSettings["WebServiceURL"];
            SJTYService sjtyService = new SJTYService();
            List<ApplicationProduct> products = sjtyService.GetAllProducts();
            foreach (ApplicationProduct product in products)
            {
                Console.WriteLine(string.Format("查询产品记录{0}::{1}", product.ProductSerialNumber.Trim(), DateTime.Now));
                try
                {
                    DataSet ds = webService.GetProductInfo(product.ProductSerialNumber);
                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        Console.WriteLine(string.Format("更新产品记录{0}::{1}::{2};{3};{4};{5};{6}",
                            product.ProductSerialNumber, DateTime.Now,
                            ds.Tables[0].Rows[0][0],
                            ds.Tables[0].Rows[0][1],
                            ds.Tables[0].Rows[0][2],
                            ds.Tables[0].Rows[0][3],
                            ds.Tables[0].Rows[0][4],
                            ds.Tables[0].Rows[0][5],
                            ds.Tables[0].Rows[0][6]));
                        LogUtility.LogUtilityIntance.LogMessgae(string.Format("更新产品记录{0}::{1}::{2};{3};{4};{5};{6}",
                            product.ProductSerialNumber, DateTime.Now,
                            ds.Tables[0].Rows[0][0],
                            ds.Tables[0].Rows[0][1],
                            ds.Tables[0].Rows[0][2],
                            ds.Tables[0].Rows[0][3],
                            ds.Tables[0].Rows[0][4],
                            ds.Tables[0].Rows[0][5],
                            ds.Tables[0].Rows[0][6]));
                        sjtyService.AddProductInfo(ds);
                    }
                }
                catch (Exception ex)
                {
                    LogUtility.LogUtilityIntance.LogException(ex, "GetProductInfo - " + product.ProductSerialNumber);
                    EmailService.SendEmail(ConfigurationManager.AppSettings["Admin"], "获取产品信息出错", string.Format("产品序列号:{0}, {1}", product.ProductSerialNumber, ex.ToString()));
                }
            }
            Console.WriteLine(string.Format("产品信息更新完成::{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("产品信息更新完成::{0}", DateTime.Now));
        }

        private static void TransferWXJL()
        {
            SMKFService.WXService webService = new WXYW.Server.SMKFService.WXService();
            webService.Url = ConfigurationManager.AppSettings["WebServiceURL"];
            SJTYService sjtyService = new SJTYService();
            //导出维修记录
            Console.WriteLine(string.Format("导入维修记录到CRM::{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("导入维修记录到CRM:::{0}", DateTime.Now));
            List<ApplicationProduct> products = sjtyService.GetApplicationProductToCRM();
            
            foreach (ApplicationProduct product in products)
            {
                string status = string.Empty;
                
                string fhType = string.Empty;
                string fhName = string.Empty;
                string fhNO = string.Empty;
                string khName = string.Empty;
                string lxrTel = string.Empty;
                string khlxr = string.Empty;
                string WXNO = string.Empty;
                string pModel = string.Empty;
                string pSerialNO = string.Empty;
                string bxqk = string.Empty;
                DateTime defaultDateTime = new DateTime(2010, 10, 10, 10, 10, 10, 10);
                DateTime fhDate = defaultDateTime;
                DateTime shTime = defaultDateTime;
                DateTime pdTime = defaultDateTime;
                string gzDes = string.Empty;
                string wxqk = string.Empty;
                string sfqk = string.Empty;
                string wxzName = string.Empty;
                DateTime FinishTime = defaultDateTime;
                DateTime qsTime = defaultDateTime;
                
                string Note = string.Empty;
                try
                {
                    if (!product.ApplicationFormReference.IsLoaded)
                    {
                        product.ApplicationFormReference.Load();
                    }
                    switch (product.SendWay)
                    {
                        case "A":
                            fhDate = product.NoticeClientDateTime.HasValue ? product.NoticeClientDateTime.Value : defaultDateTime;
                            fhType = "自提";
                            break;
                        case "B":
                            fhDate = product.SendBackTime.HasValue ? product.SendBackTime.Value : defaultDateTime;
                            if (!product.RequisitionFormReference.IsLoaded)
                            {
                                product.RequisitionFormReference.Load();
                            }
                            if (product.RequisitionForm != null)
                            {
                                fhType = product.RequisitionForm.WayOfTransport;
                                fhNO = product.RequisitionForm.RequisitionCode;
                                if (!product.RequisitionForm.LogisticCompanyReference.IsLoaded)
                                {
                                    product.RequisitionForm.LogisticCompanyReference.Load();
                                }
                                if (product.RequisitionForm.LogisticCompany != null)
                                {
                                    fhName = product.RequisitionForm.LogisticCompany.Name;
                                }
                            }
                            break;
                    }
                    if (!product.UserReference.IsLoaded)
                    {
                        product.UserReference.Load();
                    }
                    if (!product.User.ServiceStationReference.IsLoaded)
                    {
                        product.User.ServiceStationReference.Load();
                    }
                    if (!product.ProductTypeReference.IsLoaded)
                    {
                        product.ProductTypeReference.Load();
                    }
                    if (!product.QuatationForm.IsLoaded)
                    {
                        product.QuatationForm.Load();
                    }
                    double cost = 0;
                    foreach (QuatationForm quatationForm in product.QuatationForm)
                    {
                        cost += quatationForm.Cost;
                    }
                    
                    if (product.ApplySpecialService.HasValue && product.ApplySpecialService.Value)
                    {
                        sfqk = "特服";                        
                    }
                    else
                    {
                        sfqk = cost.ToString();
                    }
                    if (!product.ApplicationForm.UserReference.IsLoaded)
                    {
                        product.ApplicationForm.UserReference.Load();
                    }
                    khName = product.ApplicationForm.User.FullName;
                    lxrTel = product.ApplicationForm.User.UserMobilePhone;
                    khlxr = product.ApplicationForm.User.ContactPerson;
                    WXNO = product.ApplicationForm.ApplicationCode + RunningNumberService.TransferToRunningNumber(product.ApplicationForm.ApplicationProduct.ToList().IndexOf(product));
                    pModel = product.ProductType.ProductTypeName;
                    pSerialNO = product.ProductSerialNumber;
                    bxqk = product.ProductRepairType;
                    shTime = product.ApplicationForm.ReceiveDateTime.HasValue ? product.ApplicationForm.ReceiveDateTime.Value : defaultDateTime;
                    pdTime = product.DistributeDateTime.HasValue ? product.DistributeDateTime.Value : defaultDateTime;
                    gzDes = product.ProductProblemDescription;
                    if (!string.IsNullOrEmpty(gzDes) && gzDes.Length > 400)
                    {
                        gzDes = gzDes.Substring(0, 399);
                    }
                    wxqk = string.IsNullOrEmpty(product.BLXX)? "无":product.BLXX;
                    if (!string.IsNullOrEmpty(wxqk) && wxqk.Length > 400)
                    {
                        wxqk = wxqk.Substring(0, 399);
                    }
                    FinishTime = product.RepairCompleteDateTime.HasValue ? product.RepairCompleteDateTime.Value : DateTime.Now;
                    wxzName = product.User.ServiceStation.City;
                    qsTime = product.ClientReceiveDateTime.HasValue ? product.ClientReceiveDateTime.Value : defaultDateTime;
                    Note = product.Remark;
                    if (!string.IsNullOrEmpty(Note) && Note.Length > 300)
                    {
                        Note = product.Remark.Substring(0, 299);
                    }
                    
                    string returnValue = webService.WriteWxjl(
                        khName, WXNO, khlxr, lxrTel,pModel, 
                        pSerialNO, bxqk, shTime, pdTime, gzDes, 
                        wxqk, sfqk, FinishTime, wxzName, fhDate, 
                        fhType, fhName, qsTime, fhNO, Note);
                    if (returnValue.Equals("1"))
                    {
                        status = "OK";
                    }
                    else
                    {
                        status = returnValue;
                        //if (status.Contains("3产品型号"))
                        //{
                        //    EmailService.SendEmail(ConfigurationManager.AppSettings["Admin"], "导入数据到CRM出错", string.Format("ProductID:{0}, {1}", product.ApplicationProductID, ex.ToString()));
                        //}
                    }
                }
                catch (Exception ex)
                {
                    status = string.Format("Error:{0}", ex.Message);
                    LogUtility.LogUtilityIntance.LogException(ex, "TransferWXJL");
                    EmailService.SendEmail(ConfigurationManager.AppSettings["Admin"], "导入数据到CRM出错", string.Format("ProductID:{0}, {1}", product.ApplicationProductID, ex.ToString()));
                }
                finally
                {
                    Console.WriteLine(string.Format("维修记录:{0};{1};{2}", product.ApplicationForm.ApplicationID, product.ApplicationProductID, status));
                    LogUtility.LogUtilityIntance.LogMessgae(string.Format("维修记录:{0};{1};{2}", product.ApplicationForm.ApplicationID, product.ApplicationProductID, status));
                    SJTYLog sjtyLog = new SJTYLog();
                    sjtyLog.ApplicationFormID = product.ApplicationForm.ApplicationID;
                    sjtyLog.ApplicationProductID = product.ApplicationProductID;
                    sjtyLog.bxqk = bxqk;
                    sjtyLog.deliveNO = fhNO;
                    sjtyLog.deliverName = fhName;
                    sjtyLog.deliveTime = fhDate;
                    sjtyLog.deliveType = fhType;
                    sjtyLog.FinishTime = FinishTime;
                    sjtyLog.gzDes = gzDes;
                    sjtyLog.khlxr = khlxr;
                    sjtyLog.khName = khName;
                    sjtyLog.lxrTel = lxrTel;
                    sjtyLog.Note = Note;
                    sjtyLog.pdTime = pdTime;
                    sjtyLog.pModel = pModel;
                    sjtyLog.ProcessDate = DateTime.Now;
                    sjtyLog.pSerialNO = pSerialNO;
                    sjtyLog.qsTime = qsTime;
                    sjtyLog.sfqk = sfqk;
                    sjtyLog.shTime = shTime;
                    sjtyLog.Status = status;
                    sjtyLog.WXNO = WXNO;
                    sjtyLog.wxqk = wxqk;
                    sjtyLog.wxzName = wxzName;
                    sjtyLog.CRMID = WXNO;
                    sjtyService.AddTransferLog(sjtyLog);
                    Console.WriteLine(string.Format("维修记录导入完成:{0}", DateTime.Now));
                    LogUtility.LogUtilityIntance.LogMessgae(string.Format("维修记录导入完成:{0}", DateTime.Now));
                }
            }            
        }

        private static void GetCustomerFeedback()
        {
            SMKFService.WXService webService = new WXYW.Server.SMKFService.WXService();
            webService.Url = ConfigurationManager.AppSettings["WebServiceURL"];
            SJTYService sjtyService = new SJTYService();
            //导出维修记录
            Console.WriteLine(string.Format("开始获取客户回访信息::{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("开始获取客户回访信息:::{0}", DateTime.Now));
            List<ApplicationProduct> products = sjtyService.GetApplicationProductToHF();

            foreach (ApplicationProduct product in products)
            {
                try
                {
                    DataSet ds = webService.GetHfInfo(product.WXNO);
                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        Console.WriteLine(string.Format("获取客户回访信息::{0}", product.WXNO));
                        LogUtility.LogUtilityIntance.LogMessgae(string.Format("获取客户回访信息::{0}", product.WXNO));
                        if (!product.ApplicationFormReference.IsLoaded)
                        {
                            product.ApplicationFormReference.Load();
                        }
                        CustomerFeedback customerFeedBack = sjtyService.GetCustomerFeedback(product.WXNO);
                        if (customerFeedBack == null)
                        {
                            customerFeedBack = new CustomerFeedback();
                            customerFeedBack.ApplicationFormID = product.ApplicationForm.ApplicationID;
                            customerFeedBack.ApplicationProductID = product.ApplicationProductID;
                            customerFeedBack.hfFrom = Convert.ToString(ds.Tables[0].Rows[0]["hfFrom"]);
                            customerFeedBack.hfResult = Convert.ToString(ds.Tables[0].Rows[0]["hfResult"]);
                            customerFeedBack.hfTime = Convert.ToDateTime(ds.Tables[0].Rows[0]["hfTime"]);
                            customerFeedBack.InfoState = Convert.ToString(ds.Tables[0].Rows[0]["InfoState"]);
                            customerFeedBack.khAdvice = Convert.ToString(ds.Tables[0].Rows[0]["khAdvice"]);
                            customerFeedBack.khRequire = Convert.ToString(ds.Tables[0].Rows[0]["khRequire"]);
                            customerFeedBack.myd = Convert.ToString(ds.Tables[0].Rows[0]["myd"]);
                            customerFeedBack.RecordDate = DateTime.Now;
                            customerFeedBack.WXNO = product.WXNO;
                            sjtyService.InserCustomerFeedback(customerFeedBack);
                        }
                        else
                        {
                            customerFeedBack.ApplicationFormID = product.ApplicationForm.ApplicationID;
                            customerFeedBack.ApplicationProductID = product.ApplicationProductID;
                            customerFeedBack.hfFrom = Convert.ToString(ds.Tables[0].Rows[0]["hfFrom"]);
                            customerFeedBack.hfResult = Convert.ToString(ds.Tables[0].Rows[0]["hfResult"]);
                            customerFeedBack.hfTime = Convert.ToDateTime(ds.Tables[0].Rows[0]["hfTime"]);
                            customerFeedBack.InfoState = Convert.ToString(ds.Tables[0].Rows[0]["InfoState"]);
                            customerFeedBack.khAdvice = Convert.ToString(ds.Tables[0].Rows[0]["khAdvice"]);
                            customerFeedBack.khRequire = Convert.ToString(ds.Tables[0].Rows[0]["khRequire"]);
                            customerFeedBack.myd = Convert.ToString(ds.Tables[0].Rows[0]["myd"]);
                            customerFeedBack.RecordDate = DateTime.Now;
                            customerFeedBack.WXNO = product.WXNO;
                            sjtyService.UpdateCustomerFeedback(customerFeedBack);
                        }
                    }
                    else
                    {
                        Console.WriteLine(string.Format("获取客户回访信息::{0}::没有信息", product.WXNO));
                        LogUtility.LogUtilityIntance.LogMessgae(string.Format("获取客户回访信息::{0}::没有信息", product.WXNO));
                    }
                }
                catch (Exception ex)
                {
                    EmailService.SendEmail(ConfigurationManager.AppSettings["Admin"], "获取客户信息出错", string.Format("维修单号:{0}, {1}", product.WXNO, ex.ToString()));
                }
            }
            Console.WriteLine(string.Format("完成获取客户回访信息::{0}", DateTime.Now));
            LogUtility.LogUtilityIntance.LogMessgae(string.Format("完成获取客户回访信息:::{0}", DateTime.Now));
        }

        private static void SendPostNoticeEmail()
        {
            PostService postService = new PostService();
            List<PostSecurity> postsNeed2Notice = postService.GetPostsNeedSendNotice().ToList();
            foreach (PostSecurity postSecurity in postsNeed2Notice)
            {
                if (!postSecurity.UserTypeReference.IsLoaded)
                {
                    postSecurity.UserTypeReference.Load();
                }
                if (!postSecurity.UserType.User.IsLoaded)
                {
                    postSecurity.UserType.User.Load();
                }
                if (!postSecurity.PostReference.IsLoaded)
                {
                    postSecurity.PostReference.Load();
                }
                foreach (User user in postSecurity.UserType.User)
                {
                    string noticeSubject = string.Format(ConfigurationManager.AppSettings["NewPostEmailSubject"]);
                    string noticeBody = string.Format(ConfigurationManager.AppSettings["NewPostEmailBody"], user.ContactPerson, 
                        postSecurity.Post.Title, postSecurity.Post.Content, postSecurity.Post.PublishDate);
                    Console.WriteLine(string.Format("发送公告通知邮件:{0}::{1}", user.UserEmail, DateTime.Now));
                    //EmailService.SendEmail(user.UserEmail, noticeSubject, "<pre>" + noticeBody + "</pre>");
                    EmailService.SendEmail(user.UserEmail, noticeSubject, noticeBody);
                }
                postSecurity.MailSent = true;
                postService.UpdatePostSecurity(postSecurity);
            }
        }

        private static void CalculateAccessoryUsedTimes()
        {
            Console.WriteLine(string.Format("统计元器件使用个数:{0}", DateTime.Now));
            AccessoryService service = new AccessoryService();
            service.UpdateAccessoryUsedCount();
        }

        private static void CalculateProductRepairTimes()
        {
            Console.WriteLine(string.Format("统计产品维修次数", DateTime.Now));
            ProductService productService = new ProductService();
            productService.CalculateRepairTimes();
        }

        private static void DataCorrect()
        {
            ApplicationService applicationService = new ApplicationService();
            ApplicationProductService applicationProductService = new ApplicationProductService();
            List<ApplicationForm> applicationForms = applicationService.GetAllApplicationForm();
            foreach (ApplicationForm applicationForm in applicationForms)
            {
                Console.WriteLine(applicationForm.ApplicationCode);
                if (!applicationForm.ApplicationProduct.IsLoaded)
                {
                    applicationForm.ApplicationProduct.Load();
                }
                if (!applicationForm.GatheringReference.IsLoaded)
                {
                    applicationForm.GatheringReference.Load();
                }                

                // 检查报价时间 QuatationDatetime
                foreach (ApplicationProduct applicationProduct in applicationForm.ApplicationProduct)
                {
                    Console.WriteLine(applicationProduct.ProductSerialNumber);
                    if (!applicationProduct.QuatationForm.IsLoaded)
                    {
                        applicationProduct.QuatationForm.Load();
                    }

                    // 检查IsQuotePrice
                    if (applicationProduct.QuatationForm.Count() == 0)
                    {
                       applicationProduct.IsQuotePrice = false;
                    }
                    else
                    {
                        applicationProduct.IsQuotePrice = true;
                    }

                    // 检查QuotationDateTime
                    if (applicationProduct.QuatationForm.Count() == 0)
                    {
                        applicationProduct.QuotationDateTime = null;
                    }
                    else if (!applicationProduct.QuotationDateTime.HasValue)
                    {
                        DateTime? xx = applicationProduct.QuatationForm.Max(q => q.CreateDate);
                        if (xx.HasValue)
                        {
                            applicationProduct.QuotationDateTime = xx;
                        }
                        else if (applicationForm.QuatationDatetime.HasValue)
                        {
                            applicationProduct.QuotationDateTime = applicationForm.QuatationDatetime;
                        }
                        else if (applicationProduct.ConfirmQuotationDateTime.HasValue)
                        {
                            applicationProduct.QuotationDateTime = applicationProduct.ConfirmQuotationDateTime;
                        }
                        else
                        {
                            xx = applicationForm.ApplicationProduct.Max(q => q.QuotationDateTime);
                            if (xx.HasValue)
                            {
                                applicationProduct.QuotationDateTime = xx;
                            }
                            else
                            {
                            }
                        }
                    }

                    if (applicationProduct.IsQuotePrice.HasValue && !(applicationProduct.IsDecideToRepair.HasValue && applicationProduct.IsDecideToRepair.Value) &&
                        applicationProduct.Status == "维修完毕待发货")
                    {
                        applicationProduct.ConfirmQuotationDateTime = applicationProduct.QuotationDateTime;
                    }

                    if (applicationForm.CompleteDateTime.HasValue && !applicationProduct.RepairCompleteDateTime.HasValue)
                    {
                        applicationProduct.RepairCompleteDateTime = applicationForm.CompleteDateTime;
                    }

                    if (applicationProduct.Status == "维修完毕待发货" && !applicationProduct.RepairCompleteDateTime.HasValue)
                    {
                        applicationProduct.RepairCompleteDateTime = applicationProduct.ApplicationForm.ApplicationProduct.Max(p=>p.RepairCompleteDateTime);
                    }
                    if (applicationProduct.Status == "维修完毕待发货" && !applicationProduct.RepairCompleteDateTime.HasValue)
                    {
                        applicationProduct.RepairCompleteDateTime = applicationProduct.DistributeDateTime;
                    }
                    if (applicationProduct.Status == "返厂-待客户报价确认" && applicationProduct.ConfirmQuotationDateTime.HasValue)
                    {
                        applicationProduct.Status = "待修";
                    }

                    applicationProductService.UpdateProduct(applicationProduct);
                }
                if (!applicationForm.ApplicationProduct.IsLoaded)
                {
                    applicationForm.ApplicationProduct.Load();
                }

                DateTime? confirmquoteDatetime = applicationForm.ApplicationProduct.Max(p => p.ConfirmQuotationDateTime);
                applicationForm.ConfirmQuatationCompleteDate = confirmquoteDatetime;
                if (!applicationForm.ConfirmQuatationCompleteDate.HasValue && applicationForm.Gathering != null)
                {
                    applicationForm.ConfirmQuatationCompleteDate = applicationForm.Gathering.PayDateTime;
                }
                if (applicationForm.Status=="客户信息反馈" && applicationForm.QuatationDatetime.HasValue &&
                    !applicationForm.ConfirmQuatationCompleteDate.HasValue)
                {
                    applicationForm.ConfirmQuatationCompleteDate = applicationForm.ApplicationProduct.Max(p => p.ConfirmQuotationDateTime);
                }
                if ((applicationForm.Status == "客户信息反馈" || applicationForm.Status == "已发货待客户确认" || applicationForm.Status == "客户已收货确认") && !applicationForm.CompleteDateTime.HasValue)
                {
                    applicationForm.CompleteDateTime = applicationForm.ApplicationProduct.Max(p => p.RepairCompleteDateTime);
                }
                if ((applicationForm.Status == "维修完毕待发货" || applicationForm.Status == "客户信息反馈") && !applicationForm.CompleteDateTime.HasValue)
                {
                    applicationForm.CompleteDateTime = applicationForm.ApplicationProduct.Max(p => p.RepairCompleteDateTime);
                }
                if (applicationForm.ApplicationProduct.Where(p => p.QuatationForm.Count() > 0).Count() == 0 &&
                    applicationForm.QuatationDatetime.HasValue)
                {
                    applicationForm.QuatationDatetime = null;
                }
                if (!applicationForm.DistributeDateTime.HasValue && applicationForm.Status == "待修")
                {
                    applicationForm.DistributeDateTime = applicationForm.ApplicationProduct.Max(p => p.DistributeDateTime);
                }
                if (!applicationForm.GatheringReference.IsLoaded)
                {
                    applicationForm.GatheringReference.Load();
                }
                if (applicationForm.ApplicationProduct.Where(p => !p.RepairCompleteDateTime.HasValue).Count() == 0)
                {
                    if (applicationForm.ApplicationProduct.Where(p => p.QuotationDateTime.HasValue).Count() == 0)
                    {
                        applicationForm.Status = "维修完毕待发货";
                    }
                    else if (applicationForm.Gathering != null)
                    {
                        applicationForm.Status = "维修完毕待发货";                        
                    }
                    if (!applicationForm.CompleteDateTime.HasValue)
                    {
                        applicationForm.CompleteDateTime = applicationForm.ApplicationProduct.Max(p => p.RepairCompleteDateTime);
                    }
                }
                applicationService.UpdateApplication(applicationForm);
            }
        }
    }
}
